<template>
  <view class="review-page">
    <scroll-view scroll-y class="content-scroll">
      <!-- 评分部分 -->
      <view class="rating-section">
        <text class="rating-label">评分</text>
        <uni-rate v-model="rating" :size="48" :margin="16" :activeColor="'#FFD700'" />
      </view>

      <!-- 文本输入区域 -->
      <view class="textarea-section">
        <textarea 
          class="review-textarea"
          v-model="reviewContent"
          placeholder="请输入500字以内的内容"
          maxlength="500"
          auto-height
        ></textarea>
        <view class="char-count">{{ reviewContent.length }}/500</view>
      </view>

      <!-- 图片上传区域 -->
      <view class="upload-section">
        <view class="upload-box" @click="addImage" v-if="images.length < 9">
          <image class="camera-icon" src="/static/up-photo.png" mode="aspectFit"></image>
          <text class="upload-text">点击上传</text>
        </view>
        <view v-if="images.length > 0" class="images-gallery">
          <view 
            v-for="(img, index) in images" 
            :key="index"
            class="image-item"
          >
            <image :src="img" class="gallery-image" mode="aspectFill"></image>
            <view class="image-delete" @click.stop="removeImage(index)">
              <image class="delete-icon" src="/static/del.png" mode="aspectFit" />
            </view>
            <!-- 小程序平台覆盖层 -->
            <cover-view class="image-delete" @click.stop="removeImage(index)">
              <cover-image class="delete-icon" src="/static/del.png" />
            </cover-view>
          </view>
        </view>
        <text class="upload-tips">请上传4:3比例, 大小2m以内jpg、png图片</text>
      </view>

      <!-- 发布按钮 -->
      <view class="publish-section">
        <button class="publish-btn" :disabled="!canPublish" @click="handlePublish">
          发布
        </button>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import FileApi from '@/sheep/api/infra/file'
import BuddyApi from '@/sheep/api/member/buddy'

const orderId = ref(null)
const rating = ref(4) // 默认4星
const reviewContent = ref('')
const images = ref([])

// 判断是否可以发布
const canPublish = computed(() => {
  return rating.value > 0 && reviewContent.value.trim().length > 0
})


// 添加图片
const addImage = () => {
  const remain = 9 - images.value.length
  if (remain <= 0) {
    uni.showToast({ title: '最多选择9张图片', icon: 'none' })
    return
  }

  uni.chooseImage({
    count: remain,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
      try {
        // 验证图片大小和格式
        const validImages = []
        for (const path of res.tempFilePaths) {
          try {
            // 获取文件信息
            const fileInfo = await uni.getFileInfo({ filePath: path })
            const sizeInMB = fileInfo.size / 1024 / 1024
            
            // 检查文件大小（2MB以内）
            if (sizeInMB > 2) {
              uni.showToast({
                title: '图片大小不能超过2MB',
                icon: 'none'
              })
              continue
            }
            
            // 检查文件格式
            // 先尝试通过图片信息验证（最可靠的方式）
            let isValidImage = false
            try {
              await uni.getImageInfo({ src: path })
              isValidImage = true
            } catch (imgErr) {
              console.error('获取图片信息失败:', imgErr, '路径:', path)
            }
            
            // 如果图片信息验证失败，再检查扩展名
            if (!isValidImage) {
              const pathWithoutQuery = path.split('?')[0] // 移除查询参数
              const lastDotIndex = pathWithoutQuery.lastIndexOf('.')
              if (lastDotIndex > 0 && lastDotIndex < pathWithoutQuery.length - 1) {
                const ext = pathWithoutQuery.substring(lastDotIndex).toLowerCase()
                const validExts = ['.jpg', '.jpeg', '.png']
                if (validExts.includes(ext)) {
                  isValidImage = true
                } else {
                  console.log('不支持的格式:', ext, '路径:', path)
                }
              }
            }
            
            // 如果格式验证失败
            if (!isValidImage) {
              uni.showToast({
                title: '只支持jpg、png格式',
                icon: 'none'
              })
              continue
            }
            
            validImages.push(path)
          } catch (fileErr) {
            console.error('验证文件失败:', fileErr, path)
            // 如果获取文件信息失败，尝试直接使用图片信息验证
            try {
              await uni.getImageInfo({ src: path })
              validImages.push(path)
            } catch (imgErr) {
              console.error('验证图片失败:', imgErr)
            }
          }
        }
        
        // 上传图片
        const tasks = validImages.map(async (path) => {
          const result = await FileApi.uploadFile(path, 'buddy')
          return result?.data || null
        })
        const uploaded = (await Promise.all(tasks)).filter(Boolean)
        images.value = [...images.value, ...uploaded]
      } catch (e) {
        console.error('上传图片失败:', e)
        uni.showToast({
          title: '上传失败，请重试',
          icon: 'none'
        })
      }
    },
    fail: (err) => {
      console.error('选择图片失败:', err)
    }
  })
}

// 删除图片
const removeImage = (index) => {
  images.value.splice(index, 1)
}

// 发布评价
const handlePublish = async () => {
  if (!canPublish.value) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    })
    return
  }

  if (!orderId.value) {
    uni.showToast({
      title: '缺少订单信息',
      icon: 'none'
    })
    return
  }

  try {
    const res = await BuddyApi.submitReview({
      buddyOrderId: Number(orderId.value),
      content: reviewContent.value.trim(),
      images: images.value,
      score: rating.value
    })
    
    uni.showToast({
      title: '评价提交成功',
      icon: 'success'
    })
    
    // 延迟返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  } catch (error) {
    console.error('提交评价失败:', error)
    uni.showToast({
      title: '提交失败，请重试',
      icon: 'none'
    })
  }
}

onLoad((options) => {
  if (options.buddyOrderId) {
    orderId.value = options.buddyOrderId
  }
})
</script>

<style lang="scss" scoped>
.review-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #fff;
}

.content-scroll {
  flex: 1;
  padding: 30rpx;
  padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
  box-sizing: border-box;
}

// 评分部分
.rating-section {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
  
  .rating-label {
    font-size: 28rpx;
    color: #333;
    margin-right: 40rpx;
  }
}

// 文本输入区域
.textarea-section {
  position: relative;
  margin-bottom: 40rpx;
  
  .review-textarea {
    width: 100%;
    min-height: 300rpx;
    padding: 28rpx;
    background: rgba(249, 250, 251, 1);
    border-radius: 20rpx;
    font-size: 28rpx;
    color: #333;
    line-height: 1.6;
    box-sizing: border-box;
  }
  
  .char-count {
    position: absolute;
    bottom: 20rpx;
    right: 20rpx;
    font-size: 24rpx;
    color: #999;
  }
}

// 图片上传区域
.upload-section {
  margin-bottom: 40rpx;
  
  .upload-box {
    width: 200rpx;
    height: 200rpx;
    background: rgba(249, 250, 251, 1);
    border-radius: 16rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-bottom: 20rpx;
    
    .camera-icon {
      width: 64rpx;
      height: 64rpx;
      margin-bottom: 12rpx;
    }
    
    .upload-text {
      font-size: 24rpx;
      color: #666;
    }
  }
  
  .images-gallery {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
    margin-bottom: 20rpx;
    
    .image-item {
      position: relative;
      width: 200rpx;
      height: 200rpx;
      border-radius: 16rpx;
      overflow: hidden;
      
      .gallery-image {
        width: 100%;
        height: 100%;
      }
      
      .image-delete {
        position: absolute;
        top: 8rpx;
        right: 8rpx;
        width: 40rpx;
        height: 40rpx;
        background: rgba(0, 0, 0, 0.5);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .delete-icon {
          width: 24rpx;
          height: 24rpx;
        }
      }
    }
  }
  
  .upload-tips {
    font-size: 24rpx;
    color: #999;
    line-height: 1.5;
  }
}

// 发布按钮
.publish-section {
  margin-top: 40rpx;
  margin-bottom: 40rpx;
  
  .publish-btn {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 44rpx;
    font-size: 32rpx;
    color: #fff;
    background: linear-gradient(90deg, #B276FF 0%, #74A7FF 100%);
    border: none;
    
    &::after {
      border: none;
    }
    
    &[disabled] {
      background: #e0e0e0;
      color: #999;
    }
  }
}
</style>

